﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using Contracts.Service;
using Microsoft.Practices.Unity.InterceptionExtension;

namespace Services
{
    public class InterceptorBehaviour : IInterceptionBehavior //ICallHandler
    {
        private readonly ILogging _logging;

        public InterceptorBehaviour(ILogging logging)
        {
            _logging = logging;
        }

        public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)
        {
            Debug.WriteLine("Before method execution");
            IMethodReturn result = getNext()(input, getNext);

            if (result.Exception != null)
            {
                _logging.Log(string.Format("Exception occurred in {0}.\nParameters: {1}\nException: {2}",
                    input.MethodBase,
                    string.Join(",", input.Inputs.Cast<object>()),
                    result.Exception));
            }

            Debug.WriteLine("After method execution");
            return result;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute
        {
            get { return true; }
        }

        //public bool WillExecute { get; private set; }

        //public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
        //{
        //    Debug.WriteLine("Before method execution");
        //    IMethodReturn msg = getNext()(input, getNext);
        //    Debug.WriteLine("After method execution");
        //    return msg;
        //}

        //public int Order { get; set; }
    }
}
